﻿using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Config;
using SuperSocket.SocketEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using TestFilterSocket;

namespace server
{
    public partial class Main : Form
    {

        private HansAppServer appServer;
        private bool xintiao = true;
        private HansAppSession linshi=null;
        private SortedList<string, HansAppSession> list = new SortedList<string, HansAppSession>();
        public Main()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            HansAppServer.Encoder = Encoding.GetEncoding("gbk");
            HansAppServer.StartMark = "";
            HansAppServer.EndMark = "";
            this.appServer = new HansAppServer();
            ServerConfig serverConfig = new ServerConfig();
            IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress[] addressList = hostEntry.AddressList;

            serverConfig.Ip = ipAddress.Text.ToString();
            serverConfig.Port = Convert.ToInt32(port.Text.ToString());
            if (!this.appServer.Setup(serverConfig, null, null, null, null, null))
            {
                MessageBox.Show("开启监听端口失败");
            }
            else if (!this.appServer.Start())
            {
                MessageBox.Show("服务器开启监听失败");
            }
            else
            {

                this.appServer.NewSessionConnected += new SessionHandler<HansAppSession>(this.AppServer_NewSessionConnected);
                this.appServer.NewRequestReceived += new RequestHandler<HansAppSession, HansRequestInfo>(this.AppServer_NewRequestReceived);
                this.appServer.SessionClosed += new SessionHandler<HansAppSession, SuperSocket.SocketBase.CloseReason>(this.AppServer_SessionClosed);

                chatContent.AppendText(string.Format("服务器启动监听成功,服务器IP：{0},端口：{1}\n", this.appServer.Config.Ip, this.appServer.Config.Port));
            }

        }
        private void AppServer_SessionClosed(HansAppSession session, SuperSocket.SocketBase.CloseReason value)
        {
            string sessionIp = string.Format("{0}:{1}", session.RemoteEndPoint.Address, session.RemoteEndPoint.Port);
            string ip = session.RemoteEndPoint.Address.ToString();

            if (this.list.Keys.Contains(ip))
            {
                this.list.Remove(ip);
            }
            base.Invoke(new MethodInvoker(delegate
            {
                chatContent.AppendText(string.Format("客户端已关闭：{0},端口：{1}，原因：{2}\n", session.RemoteEndPoint.Address, session.RemoteEndPoint.Port, value));
                List<ip> iplist = new List<ip>();
                foreach (var item in list)
                {
                    ip p = new ip();
                    p.ipstr = item.Key;
                    int num = item.Key.LastIndexOf(".");
                    string a = item.Key.Substring(num + 1);
                    p.num = Convert.ToInt32(a);
                    iplist.Add(p);

                }
                var bb = iplist.OrderBy(p => p.num).ToList();
                this.listBox1.Items.Clear();
                for (int i = 0; i < bb.Count; i++)
                {
                    this.listBox1.Items.Add(bb[i].ipstr);
                }
                this.label1.Text = "设备在线数量:" + list.Count;
            }));
        }
        private void AppServer_NewSessionConnected(HansAppSession session)
        {
            string sessionIp = string.Format("{0}:{1}", session.RemoteEndPoint.Address, session.RemoteEndPoint.Port);
            string ip = session.RemoteEndPoint.Address.ToString();
            if (!this.list.Keys.Contains(ip))
            {
                this.list.Add(ip, session);
            }

            base.Invoke(new MethodInvoker(delegate
            {
                chatContent.AppendText(string.Format("\r\n客户端已连接：{0},端口：{1}", session.RemoteEndPoint.Address, session.RemoteEndPoint.Port));
                List<ip> iplist = new List<ip>();
                foreach (var item in list)
                {
                    ip p = new ip();
                    p.ipstr = item.Key;
                    int num = item.Key.LastIndexOf(".");
                    string a = item.Key.Substring(num + 1);
                    p.num = Convert.ToInt32(a);
                    iplist.Add(p);

                }
                var bb = iplist.OrderBy(p => p.num).ToList();
                this.listBox1.Items.Clear();
                for (int i = 0; i < bb.Count; i++)
                {
                    this.listBox1.Items.Add(bb[i].ipstr);
                }

                this.label1.Text = "设备在线数量:" + list.Count;
            }));
            // session.Send("Welcome");
        }
        private void AppServer_NewRequestReceived(HansAppSession session, HansRequestInfo requestInfo)
        {
            byte[] recMsg = requestInfo.Body.BodyBuffer;
            string recStr = Encoding.UTF8.GetString(recMsg);

            if (JsonSplit.IsJson(recStr))
            {
                RootObject rb = JsonConvert.DeserializeObject<RootObject>(recStr);
                if (rb.type == "send")
                {
                    linshi = session;
                    chatContent.AppendText("\r\nPC消息【" + rb.message + rb.crc16 + "】");
                    byte[] bytes = StrToHexByte(rb.message + rb.crc16);
                    if (this.list.Keys.Contains(rb.ip))
                    {
                        HansAppSession hansAppSession = this.list[rb.ip];
                     //   hansAppSession.Send(rb.message + rb.crc16);

                        hansAppSession.Send(bytes, 0, bytes.Length);
                        if (rb.id != "") {
                            session.Send(rb.id);
                        }
                    }
                    else
                    {
                        session.Send("Off");
                    }


                }
            }
            else
            {
                string result = "";
                for (int i = 0; i < recMsg.Length; i++)
                {
                    result += "" + recMsg[i].ToString("X2");
                }
                // string str = "\r\n客户端(" + session.RemoteEndPoint.Address + ") " + GetCurrentTime() + " 消息【" + result + "】";
                // chatContent.AppendText(str);


                zhixing(recMsg, result,session);
            }


        }
        private void zhixing(byte[] newbyte, string result, HansAppSession session)
        {




            if (xintiao == false && newbyte[2].ToString("X2").Equals("01") && newbyte[3].ToString("X2").Equals("02"))
            {

            }
            else
            {
                if (newbyte.Length > 3)
                {
                    chatContent.AppendText("\r\n" + result + ",代码" + newbyte[2].ToString("X2") + "," + newbyte[3].ToString("X2"));
                }
                else
                {

                    chatContent.AppendText("\r\n" + result);
                }
            }
            if (newbyte[2].ToString("X2").Equals("01") && newbyte[3].ToString("X2").Equals("01"))
            {

            }
            else if (newbyte[2].ToString("X2").Equals("01") && newbyte[3].ToString("X2").Equals("02"))
            {
                // chatContent.AppendText("\r\n" + "心跳包");
            }
            else if (newbyte[2].ToString("X2").Equals("09") && newbyte[3].ToString("X2").Equals("01"))
            {
                chatContent.AppendText("\r\n" + "窗户命令已收到");

            }
            else if (newbyte[2].ToString("X2").Equals("02") && newbyte[3].ToString("X2").Equals("01"))
            {
                chatContent.AppendText("\r\n" + "气象站返回");
                string body = result.Substring(32, result.Length - 32 - 4);
                string[] items = Util.getstr(body, 4);
                var sql = "insert into qixiang(createtime,wd,sd,fs,fx,yl,qy) values(?createtime,?wd,?sd,?fs,?fx,?yl,?qy)";
                MySqlParameter[] param = {
                                     new MySqlParameter("?createtime", MySqlDbType.String),
                                     new MySqlParameter("?wd", MySqlDbType.String),
                                     new MySqlParameter("?sd", MySqlDbType.String),
                                      new MySqlParameter("?fs", MySqlDbType.String),
                                       new MySqlParameter("?fx", MySqlDbType.String),
                                         new MySqlParameter("?yl", MySqlDbType.String),
                                           new MySqlParameter("?qy", MySqlDbType.String),

                                     };
                string time = DateTime.Now.ToLocalTime().ToString();
                param[0].Value = time;
                param[1].Value = Math.Round(System.Convert.ToInt32(items[0], 16) * 0.1, 2); //温度
                param[2].Value = Math.Round(System.Convert.ToInt32(items[1], 16) * 0.1, 2); //湿度
                param[3].Value = Math.Round(System.Convert.ToInt32(items[3], 16) * 0.1, 2);  //风速度
                param[4].Value = Math.Round(System.Convert.ToInt32(items[4], 16) * 0.1, 2);  //风向
                param[5].Value = Math.Round(System.Convert.ToInt32(items[5], 16) * 0.1, 2); //雨量
                param[6].Value = Math.Round(System.Convert.ToInt32(items[2], 16) * 0.1, 2);//气压
                SQLHelper.ExecuteNonQuery(sql, CommandType.Text, param);

                if (linshi != null)
                {
                    linshi.Send(time);
                }


            }
            else if (newbyte[2].ToString("X2").Equals("08") && newbyte[3].ToString("X2").Equals("04"))
            {
                chatContent.AppendText("\r\n" + "环流风机命令返回");
                string body = result.Substring(32, result.Length - 32 - 4);

                var root = Util.getRootObject(result);


                string[] items = Util.getstr(body, 2);


                int code = System.Convert.ToInt32(items[0], 16);
                int num = System.Convert.ToInt32(items[1], 16);
                if (num == 255)
                {
                    num = 1;
                }
                chatContent.AppendText("\r\n" + "update mock_ventilation_fan set state=" + num + " where ckbh='" + root.ckbh + "' and fan_code='" + code + "'");
                StringBuilder sql = new StringBuilder();
                sql.Append("update mock_ventilation_fan set state=?state where ckbh=?ckbh and fan_code=?fan_code");
                MySqlParameter[] param = {
                                     new MySqlParameter("?state", MySqlDbType.String),
                                     new MySqlParameter("?ckbh", MySqlDbType.String),
                                     new MySqlParameter("?fan_code", MySqlDbType.String),

                                     };
                param[0].Value = num;
                param[1].Value = root.ckbh;
                param[2].Value = code;
                SQLHelper.ExecuteNonQuery(sql.ToString(), CommandType.Text, param);

            }
            else if (newbyte[2].ToString("X2").Equals("09") && newbyte[3].ToString("X2").Equals("02"))
            {
                //窗户信息返回
                chatContent.AppendText("\r\n" + "窗户和风机命令返回");

                var root = Util.getRootObject(result);


                var end_time = DateTime.Now.ToLocalTime().ToString();
                //窗户返回结果
                string ss = newbyte[1].ToString("X2");
                if (newbyte[1].ToString("X2").Equals("14"))
                {

                    int lenss = newbyte[1];
                    string body = result.Substring(32, 4);


                    string[] items = Util.getstr(body, 2);


                    //if (mydic.ContainsKey(clientipe.Address.ToString()))
                    //{
                    //    root = mydic[clientipe.Address.ToString()];

                    //}

                    int code = System.Convert.ToInt32(items[0], 16);
                    int num = System.Convert.ToInt32(items[1], 16);
                    if (num == 255)
                    {
                        num = 1;
                    }

                    if (code <= 4)
                    {

                        chatContent.AppendText("\r\n" + result + "\r\n" + "update mock_ventilation_win set state=" + num + ",end_time='" + end_time + "' where ckbh='" + root.ckbh + "' and window_code='" + code + "'");
                        StringBuilder sql = new StringBuilder();
                        sql.Append("update mock_ventilation_fan set state=?state,end_time=?end_time where ckbh=?ckbh and fan_code=?fan_code");
                        MySqlParameter[] param = {
                                     new MySqlParameter("?state", MySqlDbType.String),
                                     new MySqlParameter("?ckbh", MySqlDbType.String),
                                     new MySqlParameter("?fan_code", MySqlDbType.String),
                                     new MySqlParameter("?end_time", MySqlDbType.String),

                                     };
                        param[0].Value = num;
                        param[1].Value = root.ckbh;
                        param[2].Value = code;
                        param[3].Value = end_time;
                        SQLHelper.ExecuteNonQuery(sql.ToString(), CommandType.Text, param);
                    }
                    //   else if (root.classname.Equals("window")&& code > 4)
                    else
                    {

                        chatContent.AppendText("\r\n" + result + "\r\n" + "update mock_ventilation_win set state=" + num + ",end_time='" + end_time + "' where ckbh='" + root.ckbh + "' and window_code='" + code + "'");
                        StringBuilder sql = new StringBuilder();
                        sql.Append("update mock_ventilation_win set state=?state,end_time=?end_time where ckbh=?ckbh and window_code=?window_code");
                        MySqlParameter[] param = {
                                     new MySqlParameter("?state", MySqlDbType.String),
                                     new MySqlParameter("?ckbh", MySqlDbType.String),
                                     new MySqlParameter("?window_code", MySqlDbType.String),
                                         new MySqlParameter("?end_time", MySqlDbType.String),

                                     };
                        param[0].Value = num;
                        param[1].Value = root.ckbh;
                        param[2].Value = code;
                        param[3].Value = end_time;
                        SQLHelper.ExecuteNonQuery(sql.ToString(), CommandType.Text, param);
                    }


                }
                else
                {

                    string body = result.Substring(32, result.Length - 32 - 4);
                    string[] items = Util.getstr(body, 2);

                    for (int i = 0; i < items.Length; i++)
                    {
                        int num = System.Convert.ToInt32(items[i], 16);
                        if (num == 255)
                        {
                            num = 1;
                        }
                        // if (i < 4 && root.classname.Equals("fan"))
                        if (i < 4)
                        {
                            chatContent.AppendText("\r\n" + result + "\r\n" + "update mock_ventilation_fan set state=" + num + ",end_time='" + end_time + "' where ckbh='" + root.ckbh + "' and fan_code='" + (i + 1) + "'");
                            StringBuilder sql = new StringBuilder();
                            sql.Append("update mock_ventilation_fan set state=?state,end_time=?end_time where ckbh=?ckbh and fan_code=?fan_code");
                            MySqlParameter[] param = {
                                         new MySqlParameter("?state", MySqlDbType.String),
                                         new MySqlParameter("?ckbh", MySqlDbType.String),
                                         new MySqlParameter("?fan_code", MySqlDbType.String),
                                         new MySqlParameter("?end_time", MySqlDbType.String),

                                          };
                            param[0].Value = num;
                            param[1].Value = root.ckbh;
                            param[2].Value = (i + 1);
                            param[3].Value = end_time;
                            SQLHelper.ExecuteNonQuery(sql.ToString(), CommandType.Text, param);
                        }
                        // else if (i >= 4 && root.classname.Equals("window"))
                        else
                        {
                            chatContent.AppendText("\r\n" + result + "\r\n" + "update mock_ventilation_win set state=" + num + ",end_time='" + end_time + "' where ckbh='" + root.ckbh + "' and window_code='" + (i + 1) + "'");
                            StringBuilder sql = new StringBuilder();
                            sql.Append("update mock_ventilation_win set state=?state,end_time=?end_time where ckbh=?ckbh and window_code=?window_code");
                            MySqlParameter[] param = {
                                     new MySqlParameter("?state", MySqlDbType.String),
                                     new MySqlParameter("?ckbh", MySqlDbType.String),
                                     new MySqlParameter("?window_code", MySqlDbType.String),
                                               new MySqlParameter("?end_time", MySqlDbType.String),

                                     };
                            param[0].Value = num;
                            param[1].Value = root.ckbh;
                            param[2].Value = (i + 1);
                            param[3].Value = end_time;
                            SQLHelper.ExecuteNonQuery(sql.ToString(), CommandType.Text, param);

                        }


                    }

                }
                if (linshi != null)
                {
                    linshi.Send("success");
                }



            }
            else if (newbyte[2].ToString("X2").Equals("09") && newbyte[3].ToString("X2").Equals("04"))
            {
                var root = Util.getRootObject(result);

                var end_time = DateTime.Now.ToLocalTime().ToString();
                //窗户返回结果
                string body = result.Substring(32, result.Length - 32 - 4);
                string[] items = Util.getstr(body, 2);


                int code = System.Convert.ToInt32(items[0], 16);
                int num = System.Convert.ToInt32(items[1], 16);
                if (num == 255)
                {
                    num = 1;
                }
                // if (code <= 4 && root.classname.Equals("fan"))
                if (code <= 4)
                {

                    chatContent.AppendText("\r\n" + result + "\r\n" + "update mock_ventilation_fan set state=" + num + ",end_time='" + end_time + "' where ckbh='" + root.ckbh + "' and fan_code='" + code + "'");
                    StringBuilder sql = new StringBuilder();
                    sql.Append("update mock_ventilation_fan set state=?state,end_time=?end_time where ckbh=?ckbh and fan_code=?fan_code");
                    MySqlParameter[] param = {
                                     new MySqlParameter("?state", MySqlDbType.String),
                                     new MySqlParameter("?ckbh", MySqlDbType.String),
                                     new MySqlParameter("?fan_code", MySqlDbType.String),
                                       new MySqlParameter("?end_time", MySqlDbType.String),

                                     };
                    param[0].Value = num;
                    param[1].Value = root.ckbh;
                    param[2].Value = code;
                    param[3].Value = end_time;
                    SQLHelper.ExecuteNonQuery(sql.ToString(), CommandType.Text, param);
                }
                else if (code > 4)
                {

                    chatContent.AppendText("\r\n" + result + "\r\n" + "update mock_ventilation_win set state=" + num + ",end_time='" + end_time + "' where ckbh='" + root.ckbh + "' and window_code='" + code + "'");
                    StringBuilder sql = new StringBuilder();
                    sql.Append("update mock_ventilation_win set state=?state,end_time=?end_time where ckbh=?ckbh and window_code=?window_code");
                    MySqlParameter[] param = {
                                     new MySqlParameter("?state", MySqlDbType.String),
                                     new MySqlParameter("?ckbh", MySqlDbType.String),
                                     new MySqlParameter("?window_code", MySqlDbType.String),
                                       new MySqlParameter("?end_time", MySqlDbType.String),

                                     };
                    param[0].Value = num;
                    param[1].Value = root.ckbh;
                    param[2].Value = code;
                    param[3].Value = end_time;
                    SQLHelper.ExecuteNonQuery(sql.ToString(), CommandType.Text, param);
                }
                if (linshi != null)
                {
                    linshi.Send("success");
                }





            }
            else if (newbyte[2].ToString("X2").Equals("07"))
            {
                var root = Util.getRootObject(result);
                //气体返回信息
                string body = result.Substring(32, result.Length - 32 - 4);
                string[] items = Util.getstr(body, 12);
                Dictionary<int, QiTi> obj = new Dictionary<int, QiTi>();

                Dictionary<string, List<int>> qiti = new Dictionary<string, List<int>>();
                List<int> o2 = new List<int>();
                List<int> co2 = new List<int>();
                List<int> ph3 = new List<int>();

                for (int i = 0; i < items.Length; i++)
                {
                    string[] arr = Util.getstr(items[i], 4);
                    o2.Add(System.Convert.ToInt32(arr[0], 16));
                    co2.Add(System.Convert.ToInt32(arr[1], 16));
                    ph3.Add(System.Convert.ToInt32(arr[2], 16));


                }
                qiti.Add("1", o2);
                qiti.Add("2", co2);
                qiti.Add("3", ph3);



              
               
                var create_date = DateTime.Now.ToLocalTime().ToString();
                var cjsj = DateTime.Now.ToLocalTime().ToString();
                var state = "1";



                foreach (KeyValuePair<string, List<int>> kvp in qiti)
                {
                    int avgzhi = Convert.ToInt32(kvp.Value.Average());

                    var gasid = System.Guid.NewGuid().ToString("N");
                    List<int> list = kvp.Value;
                    for (int i = 0; i < list.Count; i++)
                    {
                        StringBuilder sb = new StringBuilder();
                        sb.Append("insert into ln_gas_detail(id,channel,gas_id,value) values(?id,?channel,?gas_id,?value)");

                        MySqlParameter[] parametersitem = {
                                     new MySqlParameter("?id", MySqlDbType.String),
                                     new MySqlParameter("?channel", MySqlDbType.String),
                                     new MySqlParameter("?gas_id", MySqlDbType.String),
                                     new MySqlParameter("?value", MySqlDbType.String)
                                     };
                        parametersitem[0].Value = System.Guid.NewGuid().ToString("N");
                        parametersitem[1].Value = (i + 1);
                        parametersitem[2].Value = gasid;
                        parametersitem[3].Value = list[i];
                        SQLHelper.ExecuteNonQuery(sb.ToString(), CommandType.Text, parametersitem);
                    }


                    var sql = "insert into ln_gas(id,ckbh,ckmc,create_date,cjsj,czry,state,start_channel,value,end_channel,type,tag) values(?id,?ckbh,?ckmc,?create_date,?cjsj,?czry,?state,?start_channel,?value,?end_channel,?type,?tag)";
                    MySqlParameter[] parameters = {
                                     new MySqlParameter("?id", MySqlDbType.String),
                                     new MySqlParameter("?ckbh", MySqlDbType.String),
                                     new MySqlParameter("?ckmc", MySqlDbType.String),
                                     new MySqlParameter("?create_date", MySqlDbType.String),
                                     new MySqlParameter("?cjsj", MySqlDbType.String),
                                     new MySqlParameter("?czry", MySqlDbType.String),
                                     new MySqlParameter("?state", MySqlDbType.String),
                                     new MySqlParameter("?start_channel", MySqlDbType.String),
                                     new MySqlParameter("?value", MySqlDbType.String),
                                     new MySqlParameter("?end_channel", MySqlDbType.String),
                                     new MySqlParameter("?type", MySqlDbType.String),
                                     new MySqlParameter("?tag", MySqlDbType.String),


                                     };

                    parameters[0].Value = gasid;
                    parameters[1].Value = root.ckbh;
                    parameters[2].Value = root.ckmc;
                    parameters[3].Value = create_date;
                    parameters[4].Value = cjsj;
                    parameters[5].Value = root.czry;
                    parameters[6].Value = state;
                    parameters[7].Value = 1;
                    parameters[8].Value = avgzhi;
                    parameters[9].Value = 5;
                    parameters[10].Value = kvp.Key;
                    parameters[11].Value = root.id;

                    SQLHelper.ExecuteNonQuery(sql, CommandType.Text, parameters);
                }



              


            }
            else if (newbyte[2].ToString("X2").Equals("03"))
            {
                var root = Util.getRootObject(result);
                string timestr = Util.gettimestr(result);
                //温湿度检测
                string body = result.Substring(32, result.Length - 32 - 4);
                string[] items = Util.getstr(body, 4);
                double cw = Math.Round(System.Convert.ToInt32(items[1], 16) * 0.1, 2);
                double cs = Math.Round(System.Convert.ToInt32(items[0], 16) * 0.1, 2);
                double ww = Math.Round(System.Convert.ToInt32(items[3], 16) * 0.1, 2);
                double ws = Math.Round(System.Convert.ToInt32(items[2], 16) * 0.1, 2);


                List<string> list = items.ToList();
                list.RemoveRange(0, 4);
                string[] newarr = list.ToArray();

                int[] valueresult = getvalue(newarr);

                var wd_max = Math.Round(valueresult[0] * 0.1, 2);
                var wd_min = Math.Round(valueresult[1] * 0.1, 2);
                var wd_avg = Math.Round(valueresult[2] * 0.1, 2);

                //模拟数据
                // cw = wd_avg;
                // cs = getRandomNum(1, 30, 60)[0];
                // ww = wd_avg + getRandomNum(1, 5, 10)[0];
                //ws = getRandomNum(1, 30, 40)[0]; ;



                StringBuilder sb = new StringBuilder();
                sb.Append("insert into ln_temperature(id,ckbh,ckmc,create_date,cjsj,cw,cs,ww,ws,device_count,wd_max,wd_min,wd_avg,czry,state,timestr)");
                sb.Append(" values(?id,?ckbh,?ckmc,?create_date,?cjsj,?cw,?cs,?ww,?ws,?device_count,?wd_max,?wd_min,?wd_avg,?czry,?state,?timestr)");
                MySqlParameter[] param = {
                                     new MySqlParameter("?id", MySqlDbType.String),
                                     new MySqlParameter("?ckbh", MySqlDbType.String),
                                     new MySqlParameter("?ckmc", MySqlDbType.String),
                                     new MySqlParameter("?create_date", MySqlDbType.String),
                                      new MySqlParameter("?cjsj", MySqlDbType.String),
                                       new MySqlParameter("?cw", MySqlDbType.String),
                                        new MySqlParameter("?cs", MySqlDbType.String),
                                         new MySqlParameter("?ww", MySqlDbType.String),
                                          new MySqlParameter("?ws", MySqlDbType.String),
                                          new MySqlParameter("?device_count", MySqlDbType.String),
                                           new MySqlParameter("?wd_max", MySqlDbType.String),
                                            new MySqlParameter("?wd_min", MySqlDbType.String),
                                             new MySqlParameter("?wd_avg", MySqlDbType.String),
                                              new MySqlParameter("?czry", MySqlDbType.String),
                                               new MySqlParameter("?state", MySqlDbType.String),
                                                  new MySqlParameter("?timestr", MySqlDbType.String),


                                     };



                var temperature_id = System.Guid.NewGuid().ToString("N");
                param[0].Value = temperature_id;
                param[1].Value = root.ckbh;
                param[2].Value = root.ckmc;
                param[3].Value = DateTime.Now.ToLocalTime().ToString();
                param[4].Value = DateTime.Now.ToLocalTime().ToString();
                param[5].Value = cw;
                param[6].Value = cs;
                param[7].Value = ww;
                param[8].Value = ws;
                param[9].Value = items.Length - 4;
                param[10].Value = wd_max;
                param[11].Value = wd_min;
                param[12].Value = wd_avg;
                param[13].Value = root.czry;
                param[14].Value = 1;
                param[15].Value = timestr;


                SQLHelper.ExecuteNonQuery(sb.ToString(), CommandType.Text, param);
                int x = 1;
                int y = 1;
                int z = 1;

                var ln_barn_base_info = SQLHelper.GetDataSet("select * from ln_barn_base_info where ckbh='" + root.ckbh + "'").Tables[0];
                var zcount = 5;
                var ycount = 7;
                var xcount = 13;
                if (ln_barn_base_info.Rows.Count > 0)
                {
                    zcount = Convert.ToInt32(ln_barn_base_info.Rows[0]["z"]) + 1;
                    ycount = Convert.ToInt32(ln_barn_base_info.Rows[0]["y"]) + 1;
                    xcount = Convert.ToInt32(ln_barn_base_info.Rows[0]["x"]);
                }

                for (int i = 0; i < newarr.Length; i++)
                {
                    if (z % zcount == 0)
                    {
                        y = y + 1;
                        z = 1;
                    }
                    if (y == ycount)
                    {
                        y = 1;
                        x = x + 1;
                        z = 1;
                    }

                    double value = Math.Round(System.Convert.ToInt32(newarr[i], 16) * 0.1, 2);
                    StringBuilder itemsql = new StringBuilder();
                    itemsql.Append("insert into ln_temperature_detail(id,temperature_id,cjdbh,value,x,y,z)");
                    itemsql.Append("values(?id,?temperature_id,?cjdbh,?value,?x,?y,?z)");

                    MySqlParameter[] paramitem = {
                                     new MySqlParameter("?id", MySqlDbType.String),
                                     new MySqlParameter("?temperature_id", MySqlDbType.String),
                                     new MySqlParameter("?cjdbh", MySqlDbType.String),
                                     new MySqlParameter("?value", MySqlDbType.String),
                                      new MySqlParameter("?x", MySqlDbType.String),
                                       new MySqlParameter("?y", MySqlDbType.String),
                                        new MySqlParameter("?z", MySqlDbType.String),
                                };

                    paramitem[0].Value = System.Guid.NewGuid().ToString("N");
                    paramitem[1].Value = temperature_id;
                    paramitem[2].Value = (i + 1);
                    paramitem[3].Value = value;
                    paramitem[4].Value = x;
                    paramitem[5].Value = y;
                    paramitem[6].Value = z;

                    SQLHelper.ExecuteNonQuery(itemsql.ToString(), CommandType.Text, paramitem);
                    z++;
                }





                for (int j = 1; j < zcount; j++)
                {

                    List<double> center = new List<double>();
                    List<double> round = new List<double>();
                    List<double> cengarr = new List<double>();
                    var ln_temperature_detail = SQLHelper.GetDataSet("select * from ln_temperature_detail where temperature_id='" + temperature_id + "' and z=" + j).Tables[0];
                    for (int i = 0; i < ln_temperature_detail.Rows.Count; i++)
                    {

                        var startx1 = 2;
                        var startx2 = Convert.ToInt32(ln_barn_base_info.Rows[0]["x"]) - 1;


                        var starty1 = 2;
                        var starty2 = Convert.ToInt32(ln_barn_base_info.Rows[0]["y"]) - 1;

                        var itemx = Convert.ToInt32(ln_temperature_detail.Rows[i]["x"]);
                        var itemy = Convert.ToInt32(ln_temperature_detail.Rows[i]["y"]);
                        var value = Convert.ToDouble(ln_temperature_detail.Rows[i]["value"]);

                        cengarr.Add(value);
                        if (itemx >= startx1 && itemx <= startx2 && itemy >= starty1 && itemy <= starty2)
                        {
                            center.Add(value);
                        }
                        else
                        {
                            round.Add(value);

                        }

                    }
                    var layer_no = j;
                    var round_max = round.Max();
                    var round_min = round.Min();
                    var round_avg = Convert.ToInt32(round.Average());


                    var center_max = center.Max();
                    var center_min = center.Min();
                    var center_avg = Convert.ToInt32(center.Average());
                    var total_max = cengarr.Max();
                    var total_min = cengarr.Min();
                    var total_avg = Convert.ToInt32(cengarr.Average());
                    var cengid = System.Guid.NewGuid().ToString("N");
                    var cengsql = "insert into ln_temperature_statistic(id,temperature_id,layer_no,round_max,round_min,round_avg,center_max,center_min,center_avg,total_max,total_min,total_avg)"
                        + " values(?id,?temperature_id,?layer_no,?round_max,?round_min,?round_avg,?center_max,?center_min,?center_avg,?total_max,?total_min,?total_avg)";

                    MySqlParameter[] paramitem = {
                                     new MySqlParameter("?id", MySqlDbType.String),
                                     new MySqlParameter("?temperature_id", MySqlDbType.String),
                                     new MySqlParameter("?layer_no", MySqlDbType.String),
                                     new MySqlParameter("?round_max", MySqlDbType.String),
                                      new MySqlParameter("?round_min", MySqlDbType.String),
                                       new MySqlParameter("?round_avg", MySqlDbType.String),
                                        new MySqlParameter("?center_max", MySqlDbType.String),
                                         new MySqlParameter("?center_min", MySqlDbType.String),
                                          new MySqlParameter("?center_avg", MySqlDbType.String),
                                           new MySqlParameter("?total_max", MySqlDbType.String),
                                            new MySqlParameter("?total_min", MySqlDbType.String),
                                             new MySqlParameter("?total_avg", MySqlDbType.String),


                                };

                    paramitem[0].Value = System.Guid.NewGuid().ToString("N");
                    paramitem[1].Value = temperature_id;
                    paramitem[2].Value = layer_no;
                    paramitem[3].Value = round_max;
                    paramitem[4].Value = round_min;
                    paramitem[5].Value = round_avg;
                    paramitem[6].Value = center_max;
                    paramitem[7].Value = center_min;
                    paramitem[8].Value = center_avg;
                    paramitem[9].Value = total_max;
                    paramitem[10].Value = total_min;
                    paramitem[11].Value = total_avg;

                    SQLHelper.ExecuteNonQuery(cengsql, CommandType.Text, paramitem);



                }

                if (linshi != null) {
                    linshi.Send(temperature_id);
                }


            }
            else if (newbyte[2].ToString("X2").Equals("06") && newbyte[3].ToString("X2").Equals("02"))
            {
                //数量检测
                string body = result.Substring(32, result.Length - 32 - 4);
                string timestr = Util.gettimestr(result);
                double value = Math.Round(System.Convert.ToInt32(body, 16) * 0.1, 2);
                var end_time = DateTime.Now.ToLocalTime().ToString();
                StringBuilder itemsql = new StringBuilder();
                itemsql.Append("update ln_barn_num set num=?num,etime=?etime,state=?state where timestr=?timestr");


                MySqlParameter[] paramitem = {
                                     new MySqlParameter("?num", MySqlDbType.String),
                                     new MySqlParameter("?etime", MySqlDbType.String),
                                     new MySqlParameter("?state", MySqlDbType.String),
                                     new MySqlParameter("?timestr", MySqlDbType.String),

                                };
                paramitem[0].Value = value;
                paramitem[1].Value = end_time;
                paramitem[2].Value = 1;
                paramitem[3].Value = timestr;

                SQLHelper.ExecuteNonQuery(itemsql.ToString(), CommandType.Text, paramitem);

            }

            else if (newbyte[2].ToString("X2").Equals("0C") && newbyte[3].ToString("X2").Equals("01"))
            {
                var root = Util.getRootObject(result);
                string body = result.Substring(32, result.Length - 32 - 4);
                string[] items = Util.getstr(body, 8);
                string nenghaostr = "";
                for (int i = 0; i < items.Length; i++)
                {
                    int nenghao = System.Convert.ToInt32(items[i], 16);
                    nenghaostr = nenghaostr + nenghao + ",";

                }
                if (!nenghaostr.Equals(""))
                {
                    nenghaostr = nenghaostr.Substring(0, nenghaostr.Length - 1);
                }

                StringBuilder itemsql = new StringBuilder();
                itemsql.Append("update ln_barn_base_info set nenghao=?nenghao where ckbh=?ckbh");


                MySqlParameter[] paramitem = {
                                     new MySqlParameter("?nenghao", MySqlDbType.String),
                                     new MySqlParameter("?ckbh", MySqlDbType.String),


                                };
                paramitem[0].Value = nenghaostr;
                paramitem[1].Value = root.ckbh;

                SQLHelper.ExecuteNonQuery(itemsql.ToString(), CommandType.Text, paramitem);

                if (linshi != null)
                {
                    linshi.Send(nenghaostr);
                }

            }
        }



        public int[] getRandomNum(int num, int minValue, int maxValue)
        {
            if ((maxValue + 1 - minValue - num < 0))
                maxValue += num - (maxValue + 1 - minValue);
            Random ra = new Random(unchecked((int)DateTime.Now.Ticks));
            int[] arrNum = new int[num];
            int tmp = 0;
            StringBuilder sb = new StringBuilder(num * maxValue.ToString().Trim().Length);

            for (int i = 0; i <= num - 1; i++)
            {
                tmp = ra.Next(minValue, maxValue);
                while (sb.ToString().Contains("#" + tmp.ToString().Trim() + "#"))
                    tmp = ra.Next(minValue, maxValue + 1);
                arrNum[i] = tmp;
                sb.Append("#" + tmp.ToString().Trim() + "#");
            }
            return arrNum;
        }
        public int[] getvalue(string[] items)
        {
            int[] arr = new int[items.Length];
            int avg = 0;
            for (int i = 0; i < items.Length; i++)
            {

                arr[i] = System.Convert.ToInt32(items[i], 16);
                avg += arr[i];

            }

            avg = avg / arr.Length;
            ArrayList list = new ArrayList(arr);
            list.Sort();
            int min = Convert.ToInt32(list[0]);
            int max = Convert.ToInt32(list[list.Count - 1]);

            int[] result = new int[3];
            result[0] = max;
            result[1] = min;
            result[2] = avg;


            return result;


        }

        private void WriteLog(string text)
        {

            string path = AppDomain.CurrentDomain.BaseDirectory;
            path = System.IO.Path.Combine(path
            , "Logs\\");

            if (!System.IO.Directory.Exists(path))
            {
                System.IO.Directory.CreateDirectory(path);
            }
            string fileFullName = System.IO.Path.Combine(path
            , string.Format("{0}.txt", DateTime.Now.ToString("yyyyMMdd-HHmm")));


            using (StreamWriter output = System.IO.File.AppendText(fileFullName))
            {
                output.WriteLine(text);

                output.Close();
            }
        }




        /// <summary>
        /// 获取当前系统时间的方法
        /// </summary>
        /// <returns>当前时间</returns>
        private DateTime GetCurrentTime()
        {
            DateTime currentTime = new DateTime();
            currentTime = DateTime.Now;
            return currentTime;
        }
        private string byteToHexStr(byte[] bytes)
        {
            string returnStr = "";
            if (bytes != null)
            {
                for (int i = 0; i < bytes.Length; i++)
                {
                    returnStr += bytes[i].ToString("X2");//ToString("X2") 为C#中的字符串格式控制符
                }
            }
            return returnStr;
        }
        public byte[] StrToHexByte(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
        }
        private void Main_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (this.checkBox1.Checked)
            {
                xintiao = false;
            }
            else
            {
                xintiao = true;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.chatContent.Text = "";
        }
    }
}
